package com.liuchuanzheng.lcz_wanandroid.room

import androidx.room.Room
import androidx.room.Transaction
import com.liuchuanzheng.lcz_wanandroid.App
import com.liuchuanzheng.lcz_wanandroid.module.home.bean.Article

/**
 * @author 刘传政
 * @date 2021/9/22 0022 14:26
 * QQ:1052374416
 * 电话:18501231486
 * 作用:
 * 注意事项:
 */
object RoomHelper {
    private val appDatabase by lazy {
        Room.databaseBuilder(
            App.instance,
            AppDatabase::class.java, "db_lcz_wanandroid"
        ).build()
    }
    private val readHistoryDao by lazy { appDatabase.readHistoryDao() }
    //其实是操作两个表 article和tag。article和tag是一对多关系
    @Transaction
    suspend fun addReadHistory(article: Article) {
        article.readTime = System.currentTimeMillis()
        readHistoryDao.insertArticle(article)
        article.tags.forEach { tag ->
            tag.articleId = article.id
            readHistoryDao.insertTag(tag)
        }
    }
    @Transaction
    suspend fun queryAllReadHistory(): List<Article> {
        return readHistoryDao.queryAllReadHistory().map {
            it.article.apply {
                tags = it.tags
            }
        }
    }
    suspend fun deleteReadHistory(article: Article) {
        readHistoryDao.queryReadHistory(article.id)?.let { readHistory ->
            readHistoryDao.deleteArticle(readHistory.article)
            readHistory.tags.forEach {
                readHistoryDao.deleteTag(it)
            }
        }
    }
}